package vn.lumi.smarthome.ui;

import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.DatabaseHelper;
import vn.lumi.smarthome.io.database.TBL_Device;
import vn.lumi.smarthome.io.database.TBL_DeviceState;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Device.OnActiveListener;
import vn.lumi.smarthome.io.model.Device.OnChangeSpeedListener;
import vn.lumi.smarthome.ulti.LogUltis;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class DeviceFragment extends BaseFragment implements
		LoaderCallbacks<Cursor>, OnActiveListener, OnChangeSpeedListener {
	private static final String TAG = "DeviceFragment";

	private static DeviceFragment sDeviceFragment;
	
	//Khai bao cac tham so chua View
	private ListView mlistDevices;

	// Khai bao bien luu adapter cho listview
	private DeviceAdapter mDeviceAdapter;

	//Khai bao ID cua Loader
	private static final int LOADER_ID=1;

	/**
	 * 
	 * @param floor_id
	 * @param room_id
	 * @return
	 */
	public static DeviceFragment newInstance(int floor_id, int room_id) {
		LogUltis.i(TAG, "create DeviceFragment");
		if (sDeviceFragment == null) {
			sDeviceFragment = new DeviceFragment();
		}
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, floor_id);
		bundle.putInt(ROOM_ID, room_id);
		sDeviceFragment.setArguments(bundle);
		return sDeviceFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mFloor_id = getArguments().getInt(FLOOR_ID);
		mRoom_id = getArguments().getInt(ROOM_ID);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_device, container, false);
		init_view(view);
		refreshData(mFloor_id, mRoom_id);
		return view;
	}
	
	private void init_view(View view){
		mlistDevices=(ListView)view.findViewById(R.id.fragment_device_list);
		
		mDeviceAdapter=new DeviceAdapter(getActivity(), null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		mDeviceAdapter.setActiveListener(this);
		mDeviceAdapter.setChangeSpeedListener(this);
		
		mlistDevices.setAdapter(mDeviceAdapter);
	}
	@Override
	public void refreshData(int floor_id,int room_id){
		mFloor_id=floor_id;
		mRoom_id=room_id;
		Bundle bundle=new Bundle();
		bundle.putInt(FLOOR_ID, mFloor_id);
		bundle.putInt(ROOM_ID, mRoom_id);
		getLoaderManager().restartLoader(LOADER_ID, bundle, this);
		mDeviceAdapter.swapCursor(null);
	}
	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle bundle) {
		String selection=DatabaseHelper.DB_TBL_DEVICE+"."+TBL_Device.ROOM_ID+"=?";
		int room_id=bundle.getInt(ROOM_ID);
		LogUltis.i(TAG, "Room_id to Loader="+room_id);
		
		String[] selectionArgs=new String[]{room_id+""};
		return new CursorLoader(getActivity(), TBL_Device.CONTENT_URI_DEVICES, null, selection, selectionArgs, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		if(cursor!=null){
			LogUltis.i(TAG, "cursor !=null");
			LogUltis.i(TAG, "num rows="+cursor.getCount());
			mDeviceAdapter.swapCursor(cursor);
		}else{
			LogUltis.i(TAG, "cursor =null");
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mDeviceAdapter.swapCursor(null);
	}
	
	@Override
	public void onActive(Device device, boolean value) {
		ContentValues values = new ContentValues();
		values.put(TBL_Device.IS_CONTROL, 1);
		
		String selection=TBL_Device._ID+"=?";
		String[] selectionArgs=new String[]{device.getId()+""};
		
		getActivity().getContentResolver().update(TBL_Device.CONTENT_URI_DEVICES, values, selection, selectionArgs);
		
		values.clear();
		LogUltis.i(TAG, "Value="+value);
		LogUltis.i(TAG, "state_id["+device.getState_id()+"]");
		
		LogUltis.i(TAG, "===========DEVICE========");
		LogUltis.i(TAG, "device_name="+device.getName());
		LogUltis.i(TAG, "device_id="+device.getId());
		LogUltis.i(TAG, "device_type="+device.getType_id());
		LogUltis.i(TAG, "room_id="+device.getRoom_id());
		LogUltis.i(TAG, "device_STATEid="+device.getState_id());
		LogUltis.i(TAG, "==============================");
		
		if(value)
			values.put(TBL_DeviceState.VALUE, 1);
		else
			values.put(TBL_DeviceState.VALUE, 0);
		
		selection=TBL_DeviceState._ID+"=?";
		selectionArgs=new String[]{device.getState_id()+""};
		
		new MyThread(getActivity(), values, selection, selectionArgs,device).start();
		
	}
	
	public class MyThread extends Thread{
		private Context context;
		private ContentValues mContentValues;
		private String mSelection;
		private String[] mSelectionArgs;
		private Device device;
		public MyThread(Context context,ContentValues contentValues,String selection,String[] selectionArgs,Device device) {
			this.context=context;
			mContentValues=contentValues;
			mSelection=selection;
			mSelectionArgs=selectionArgs;
			this.device=device;
		}
		
		@Override
		public void run() {
			super.run();
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ContentValues values=new ContentValues();
			values.put(TBL_Device.IS_CONTROL, 0);

			String s1=TBL_Device._ID+"=?";
			String[] s2=new String[]{device.getId()+""};
			
			int e=context.getContentResolver().update(TBL_Device.CONTENT_URI_DEVICES, values, s1,s2);
			int effect=context.getContentResolver().update(TBL_DeviceState.CONTENT_URI_DEVICE_STATE, mContentValues, mSelection,mSelectionArgs);
			LogUltis.e(TAG, "Effect="+effect);
			
		}
	}
	
	@Override
	public void onChangeSpeed(Device device, int speed) {
		Toast.makeText(getActivity(), "Name["+device.getName()+"] speed=["+speed+"]", Toast.LENGTH_SHORT).show();
	}

	private static class DeviceAdapter extends MyCursorAdapter {
		private static final String TAG = "DeviceAdapter";

		private OnActiveListener mOnActiveListener;
		private OnChangeSpeedListener mOnSpeedListener;

		public DeviceAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
		}
		
		public void setActiveListener(OnActiveListener activeListener){
			mOnActiveListener=activeListener;
		}
		public void setChangeSpeedListener(OnChangeSpeedListener changeSpeedListener){
			mOnSpeedListener=changeSpeedListener; 
		}
		@Override
		public boolean isEnabled(int position) {
			return false;
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup arg2) {
			int layout_type=getItemViewType(cursor);
//			int layout_type=Device.getLayoutType(device_type);
			View view=null;
			
			switch (layout_type) {
			case Device.TYPE_LAYOUT_ONOFF:
				view=View.inflate(context, R.layout.item_listview_device_onoff, null);
				break;
			case Device.TYPE_LAYOUT_RGB:
				view=View.inflate(context, R.layout.item_list_device_rgb, null);
				break;
			case Device.TYPE_LAYOUT_DIMMER:
				view=View.inflate(context, R.layout.item_list_device_dimmer, null);
				break;

			case Device.TYPE_LAYOUT_BLIND:
				view=View.inflate(context, R.layout.item_list_device_blind, null);
				break;
				
			default:
				break;
				}
			return view;
		}
		@Override
		public void bindView(View view, Context context,Cursor cursor) {
			int layout_type=getItemViewType(cursor);
			int device_type=cursor.getInt(cursor.getColumnIndex(TBL_Device.TYPE_ID));
			final Device device=getDevice(cursor);
			
			switch (layout_type) {
			case Device.TYPE_LAYOUT_ONOFF:
				TextView textView=(TextView)view.findViewById(R.id.item_listview_device_onoff_txt_name);
				textView.setText(device.getName());
				
				final ImageView imgage=(ImageView)view.findViewById(R.id.item_listview_device_onoff_img_onoff);
				if(device.isControl()){
					imgage.setPressed(true);
				}
				else{
					imgage.setPressed(false);
				}
				final int value=device.getDeviceState().getValue();
				if(value==1){
					imgage.setImageResource(R.drawable.img_light_off_selector);
				}else{
					imgage.setImageResource(R.drawable.img_light_on_selector);
				}
					
				imgage.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						if(value==0){
							mOnActiveListener.onActive(device, true);
						}else{
							mOnActiveListener.onActive(device, false);
						}
						
					}
				});
				break;
			case Device.TYPE_LAYOUT_DIMMER:
				TextView text=(TextView)view.findViewById(R.id.item_listview_device_valuechange_txt_name);
				text.setText(device.getName());
				SeekBar seekBar=(SeekBar)view.findViewById(R.id.item_listview_device_valuechange_seekbar_change);
				seekBar.setMax(7);
				seekBar.setProgress(device.getDeviceState().getValue());
				
				final ImageView img=(ImageView)view.findViewById(R.id.item_listview_device_valuechange_img_onoff);
				
				if(device.isControl()){
					img.setPressed(true);
				}
				else{
					img.setPressed(false);
				}
				final int value2=device.getDeviceState().getValue();
				if(value2==1){
					switch (device_type) {
					case Device.DEVICE_TYPE_DIMMER:
						img.setImageResource(R.drawable.img_dimmer_off_selector);
						break;
					case Device.DEVICE_TYPE_FAN:
						img.setImageResource(R.drawable.img_fan_off_selector);
						break;
					case Device.DEVICE_TYPE_AIRCON:
						img.setImageResource(R.drawable.img_aircon_off_selector);
						break;
					default:
						break;
					}
					
				}else{
					switch (device_type) {
					case Device.DEVICE_TYPE_DIMMER:
						img.setImageResource(R.drawable.img_dimmer_on_selector);
						break;
					case Device.DEVICE_TYPE_FAN:
						img.setImageResource(R.drawable.img_fan_on_selector);
						break;
					case Device.DEVICE_TYPE_AIRCON:
						img.setImageResource(R.drawable.img_aircon_on_selector);
						break;
					default:
						break;
					}
					
				}
				img.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if(value2==0){
							mOnActiveListener.onActive(device, true);
						}else{
							mOnActiveListener.onActive(device, false);
						}
					}
				});
				break;
			case Device.TYPE_LAYOUT_RGB:
				TextView text2=(TextView)view.findViewById(R.id.item_list_device_rgb_txt_name);
				text2.setText(device.getName());
				final ImageView image=(ImageView)view.findViewById(R.id.item_list_device_rgb_img_onoff);
				if(device.isControl()){
					image.setPressed(true);
				}
				else{
					image.setPressed(false);
				}
				final int v2=device.getDeviceState().getValue();
				if(v2==1){
					image.setImageResource(R.drawable.img_rgb_off_selector);
				}else{
					image.setImageResource(R.drawable.img_rgb_on_selector);
				}
					
				image.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						if(v2==0){
							mOnActiveListener.onActive(device, true);
						}else{
							mOnActiveListener.onActive(device, false);
						}
						
					}
				});
				break;
			case Device.TYPE_LAYOUT_BLIND:
				TextView text3=(TextView)view.findViewById(R.id.item_list_device_blind_txt_name);
				ImageView i=(ImageView)view.findViewById(R.id.item_list_device_blind_img_onoff);
				if(text3!=null)
					text3.setText(device.getName());
				int v=device.getDeviceState().getValue();
				if(v>1){
					i.setImageResource(R.drawable.blind_9);
				}else{
					i.setImageResource(R.drawable.blind_1);
				}
				
				break;
			default:
				break;
				}
		}
	
	}

}
